/* 用于处理错误的函数 */
const app = require("../app");

const log4js = require("../utils/log4j");

const {
  ACCOUNT_OR_PASSWORD_IS_REQUIRED,
  ACCOUNT_IS_ALREADY_EXISTS,
  ACCOUNT_IS_NOT_EXISTS,
  PASSWORD_IS_INCORRENT,
  UNAUTHORIZATION,
  OPERATION_IS_NOT_ALLOWED,
  PARAMETER_ERROR,
  PARAMETER_MISSING,
  refreshToken_IS_INVALID,
  accessToken_IS_INVALID,
  accessToken_IS_REQUIRED,
  refreshToken_IS_REQUIRED,
} = require("../config/error-constants");

// 封装错误处理函数
const errorHandler = (error, ctx, param = []) => {
  let code = 0;
  let message = "";

  switch (error) {
    case ACCOUNT_OR_PASSWORD_IS_REQUIRED:
      code = -1001;
      message = "用户名或者密码不能为空~";
      break;
    case ACCOUNT_IS_ALREADY_EXISTS:
      code = -1002;
      message = "该账号名被占用了，请重新注册~";
      break;
    case ACCOUNT_IS_NOT_EXISTS:
      code = -1003;
      message = "用户名不存在，请检查用户名是否正确~";
      break;
    case PASSWORD_IS_INCORRENT:
      code = -1004;
      message = "密码错误，请检查用户名和密码是否匹配~";
      break;
    case UNAUTHORIZATION:
      code = -1005;
      message = "无效的token或者token已经过期~";
      break;
    case OPERATION_IS_NOT_ALLOWED:
      code = -1006;
      message = "没有操作该资源的权限~";
      break;
    case refreshToken_IS_INVALID:
      code = -1007;
      message = "长token失效,请重新登录~";
      break;
    case accessToken_IS_INVALID:
      code = -1008;
      message = "短token失效,没有操作该资源的权限~";
      break;
    case refreshToken_IS_REQUIRED:
      code = -1009;
      message = "长token不能为空~";
      break;
    case accessToken_IS_REQUIRED:
      code = -1010;
      message = "短token不能为空~";
      break;
    case PARAMETER_ERROR:
      code = -1011;
      message = "参数错误~";
      break;
    case PARAMETER_MISSING:
      console.log("handleError", param);
      code = -1012;
      message = `缺少参数${param}`;
      break;
  }

  log4js.error(message);

  ctx.body = { code, message };
};

// app监听错误事件
app.on("error", errorHandler);
